/**
 * 
 */
package edu.gtcfla.km.appmodules.service.impl;

import java.io.File;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import org.apache.tools.ant.util.FileUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.vsg.biz.BusinessOperationException;

import edu.gtcfla.km.UploadFile;
import edu.gtcfla.km.appmodules.service.AttachmentService;
import edu.gtcfla.km.repositories.UploadFileRepo;

/**
 * @author vison
 *
 */
public class AttachmentServiceI implements AttachmentService , InitializingBean {

	@Autowired	
	private UploadFileRepo uploadFileRepo;
	
	
	private String saveServerPath;
	
	public String getSaveServerPath() {
		return saveServerPath;
	}

	public void setSaveServerPath(String saveServerPath) {
		this.saveServerPath = saveServerPath;
	}

	private File uploadPath;

	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		uploadPath = new File(saveServerPath);
		if (!uploadPath.exists()) {
			uploadPath.mkdirs();
		}

	}	

	/* (non-Javadoc)
	 * @see edu.gtcfla.km.appmodules.service.AttachmentService#deleteFiles(java.lang.String[])
	 */
	@Override
	public void deleteFiles(String[] receiveValues)
			throws BusinessOperationException {
		// TODO Auto-generated method stub
		
		Set<String> fileIds = new LinkedHashSet<String>();
		
		for (String value : receiveValues) {
			fileIds.add( value );
		}
		
		Map<String, UploadFile> uploadfiles =  uploadFileRepo.findAllMapByIds( fileIds );
		
		
		// --- remote files ---
		for (UploadFile uf : uploadfiles.values()) {
			File localFile = new File(uploadPath , uf.getFileName());
			FileUtils.delete(localFile );
		}
		
		
		// --- delete data in database ---
		for (UploadFile uf : uploadfiles.values()) {
			uploadFileRepo.delete(uf);
		}
		
		
	}

}
